package com.itheima.Task;

import com.itheima.common.constant.RedisConstant;
import com.itheima.common.utils.AliOssUtil;
import com.itheima.service.SetmealService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.List;
import java.util.Set;

@Component
public class TimeTask {


    @Autowired
    RedisTemplate redisTemplate;
    @Autowired
    AliOssUtil aliOssUtil;
    @Autowired
    SetmealService setmealService;

    /**
     * 定时任务的使用
     * @author pan_junbiao
     **/

        @Scheduled(cron="*/20 * * * * *")   //每天凌晨2点执行一次0 0 2 * * ?
        public void execute(){

            System.out.println("定时任务执行了..."+new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(System.currentTimeMillis()));


            //            将数据库里的图片URL保存在Redis的set集合中
            List<String> imgURL = setmealService.findAllImgURL();
            for(String pic : imgURL){
                redisTemplate.opsForSet().add(RedisConstant.SETMEAL_PIC_DB_RESOURCES,pic);
            }



//            删除多余图片从阿里云删除
            Set<String> result =  redisTemplate.opsForSet().difference(RedisConstant.SETMEAL_PIC_RESOURCES,RedisConstant.SETMEAL_PIC_DB_RESOURCES);
            for(String pic : result){

//                从文件路径中获取图片名称
                String picName = pic.substring(pic.lastIndexOf("/")+1);
                aliOssUtil.delete(picName);
//                删除redis中多余的图片名称
                redisTemplate.opsForSet().remove(RedisConstant.SETMEAL_PIC_RESOURCES,pic);

            }
//            清空redis中DB的所有内容
            redisTemplate.delete(RedisConstant.SETMEAL_PIC_DB_RESOURCES);
            System.out.println("定时任务执行完毕..."+new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(System.currentTimeMillis()));
        }
}




